package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Minicat的主类
 */
public class Bootstrap {

    /**定义socket监听的端口号*/
    private int port = 8080;

    private Service service = new Service();

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }


    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {
        //加载解析server.xml
        loadServer("server.xml");
        // 加载解析相关的配置，web.xml
        loadInternalServlet("web.xml");
        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );
        /*
            完成Minicat 1.0版本
            需求：浏览器请求http://localhost:8080,返回一个固定的字符串到页面"Hello Minicat!"
         */
        ServerSocket serverSocket = new ServerSocket(service.getPort());
        System.out.println("=====>>>Minicat start on port：" + service.getPort());
        /*while(true) {
            Socket socket = serverSocket.accept();
            // 有了socket，接收到请求，获取输出流
            OutputStream outputStream = socket.getOutputStream();
            String data = "Hello Minicat!";
            String responseText = HttpProtocolUtil.getHttpHeader200(data.getBytes().length) + data;
            outputStream.write(responseText.getBytes());
            socket.close();
        }*/
        /**
         * 完成Minicat 2.0版本
         * 需求：封装Request和Response对象，返回html静态资源文件
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            response.outputHtml(request.getUrl());
            socket.close();

        }*/


        /**
         * 完成Minicat 3.0版本
         * 需求：可以请求动态资源（Servlet）
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            // 静态资源处理
            if(servletMap.get(request.getUrl()) == null) {
                response.outputHtml(request.getUrl());
            }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = servletMap.get(request.getUrl());
                httpServlet.service(request,response);
            }

            socket.close();

        }
*/

        /*
            多线程改造（不使用线程池）
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket,servletMap);
            requestProcessor.start();
        }*/
        System.out.println("=========>>>>>>使用线程池进行多线程改造");
        /*
            多线程改造（使用线程池）
         */
        while(true) {
            Socket socket = serverSocket.accept();
//            RequestProcessor requestProcessor = new RequestProcessor(socket,servletMap);
            RequestProcessor requestProcessor = new RequestProcessor(socket, service);
            //requestProcessor.start();
            threadPoolExecutor.execute(requestProcessor);
        }



    }

    private void loadWebapp(Host host) {
        File baseRoot = new File(host.getAppBase());
        for(File app : baseRoot.listFiles()) {
            if (app.exists()) {
                if (app.isDirectory()) {
                    Context context = new Context();
                    context.setPath(app.getName());//将项目名作为context   例如：/demo1/test
                    String classPathName = app.getAbsolutePath() + File.separator + "WEB-INF" + File.separator + "classes";
                    File classPath = new File(classPathName);
                    if(classPath.exists()){
                        //初始化类加载器并加载该项目下的所有类
                        WebAppClassLoader webAppClassLoader = new WebAppClassLoader(classPathName);
                        File webXml = new File(classPath+File.separator+"web.xml");
                        if(webXml.exists() && webXml.isFile()){
                            loadExternalServlet(webXml.getAbsolutePath(),context,webAppClassLoader);
                        }
                    }
                    host.getContextMap().put(context.getPath(),context);
                }
            }
        }
    }

    private void loadServer(String path) {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(path);
        if(resourceAsStream == null){
            try {
                FileInputStream fileInputStream = new FileInputStream(new File(path));
                resourceAsStream = new BufferedInputStream(fileInputStream);
            }catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        SAXReader saxReader = new SAXReader();

        try{
            //读取文件流
            Document doc = saxReader.read(resourceAsStream);
            Element rootElement = doc.getRootElement();//<server>
            List<Element> serviceList = rootElement.selectNodes("service");
            for (int i = 0; i < serviceList.size(); i++) {
                Element serviceNode = serviceList.get(i);
                String serviceName = serviceNode.attributeValue("name");//catalina
                List<Element> list = serviceNode.selectNodes("connector");//<connector>
                if(list.size() > 0){
                    Element element = list.get(0);
                    service.setPort( Integer.valueOf(element.attributeValue("port")));
                }
                List<Element> hostNodes = serviceNode.selectNodes("host");//<host>
                if (hostNodes.size() > 0){
                    Element hostNode = hostNodes.get(0);
                    Host host = new Host();
                    host.setName(hostNode.attributeValue("name"));
                    host.setAppBase(hostNode.attributeValue("appBase"));
                    //加载webapp下部署的项目，封装到host中
                    loadWebapp(host);
                    service.setHost(host);
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }


    /**
     * 加载解析web.xml，初始化Servlet
     */
    private void loadInternalServlet(String webPath) {
        Context context = new Context();
        context.setPath("");
        loadServlet(webPath,context,null);
        service.getHost().getContextMap().put(context.getPath(),context);
    }

    private void loadExternalServlet(String webPath,Context context, WebAppClassLoader webAppClassLoader) {
        loadServlet(webPath,context,webAppClassLoader);
    }

    private void loadServlet(String webPath,Context context,WebAppClassLoader classLoader){
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(webPath);
        if(resourceAsStream == null){
            try {
                FileInputStream fileInputStream = new FileInputStream(new File(webPath));
                resourceAsStream = new BufferedInputStream(fileInputStream);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element =  selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();
                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                try{
                    context.getServletMap().put(urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());
                }catch (ClassNotFoundException e) {
                    try {
                        context.getServletMap().put(urlPattern, (HttpServlet) classLoader.findClass(servletClass).newInstance());
                    } catch (ClassNotFoundException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }

    }

    /**
     * Minicat 的程序启动入口
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
